"""
AI聊天API路由
"""
import logging
from fastapi import APIRouter, Depends, HTTPException, BackgroundTasks
from sqlalchemy.orm import Session
from pydantic import BaseModel
from typing import List, Dict, Any

from app.database import get_db
from app.models.user import User
from app.api.auth import get_current_user
from app.services.chat_service import chat_service

logger = logging.getLogger(__name__)

router = APIRouter()


class ChatRequest(BaseModel):
    """聊天请求"""
    question: str
    include_context: bool = True  # 是否包含上下文


class ChatResponse(BaseModel):
    """聊天响应"""
    answer: str
    context_used: List[Dict[str, Any]]
    response_time: float


class InsightResponse(BaseModel):
    """洞察分析响应"""
    analysis: str
    diary_count: int
    analysis_period: str


@router.post("/chat", response_model=ChatResponse)
async def chat_with_ai(
    request: ChatRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    与AI助手对话
    """
    try:
        import time
        start_time = time.time()
        
        context_data = []
        
        if request.include_context:
            # 搜索相关的日记内容
            context_data = await chat_service.search_similar_content(
                db=db,
                user_id=current_user.id,
                query=request.question,
                limit=5
            )
            logger.info(f"找到 {len(context_data)} 个相关上下文")
        
        # 基于上下文生成回答
        answer = await chat_service.chat_with_context(
            question=request.question,
            context_data=context_data
        )
        
        response_time = time.time() - start_time
        
        return ChatResponse(
            answer=answer,
            context_used=context_data,
            response_time=round(response_time, 2)
        )
        
    except Exception as e:
        logger.error(f"AI聊天失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"AI聊天服务异常: {str(e)}")


@router.get("/insights", response_model=InsightResponse)
async def get_personal_insights(
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    获取个人洞察分析
    """
    try:
        insights = await chat_service.generate_insights(
            db=db,
            user_id=current_user.id
        )
        
        if "error" in insights:
            raise HTTPException(status_code=500, detail=insights["error"])
        
        if "message" in insights:
            # 暂无足够数据
            return InsightResponse(
                analysis=insights["message"],
                diary_count=0,
                analysis_period=""
            )
        
        return InsightResponse(
            analysis=insights["analysis"],
            diary_count=insights["diary_count"],
            analysis_period=insights["analysis_period"]
        )
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"洞察分析失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"洞察分析服务异常: {str(e)}")


@router.post("/search")
async def search_diary_content(
    request: ChatRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    搜索相关日记内容（不进行AI对话）
    """
    try:
        results = await chat_service.search_similar_content(
            db=db,
            user_id=current_user.id,
            query=request.question,
            limit=10
        )
        
        return {
            "query": request.question,
            "results": results,
            "total": len(results)
        }
        
    except Exception as e:
        logger.error(f"日记搜索失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"搜索服务异常: {str(e)}")


@router.get("/models")
async def get_available_models():
    """
    获取可用的AI模型信息
    """
    return {
        "embedding_model": {
            "name": "text-embedding-v4",
            "provider": "阿里云百炼",
            "dimensions": 1024,
            "max_tokens": 8192,
            "price": "0.0005元/千Token"
        },
        "chat_model": {
            "name": "qwen-turbo",
            "provider": "阿里云百炼",
            "context_length": 8192,
            "price": "0.0015元/千Token（输入）+ 0.002元/千Token（输出）"
        }
    } 